﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RMS.Utils.Dicom.Commen;
namespace RMS.Utils.Dicom.DataStructure
{
    public class ValueLength
    {
        #region [Properties]
        private VR vr;
        private int _valueLength;

        public int Length
        {
            get
            {
                return _valueLength;
            }
        }
        public bool IsUndefined
        {
            get { return _valueLength < 0; }
        }
        #endregion

        #region [Constructor]
        public ValueLength(VR vr)
        {
            this.vr = vr;
            this.ReadValueLenght();
        }
        #endregion
        #region [HelperMethod]
        private void ReadValueLenght()
        {

            bool isCertainVR = vr.Name.Equals("OB") || vr.Name.Equals("OW") ||
                vr.Name.Equals("OF") || vr.Name.Equals("SQ") ||
                vr.Name.Equals("UT");
            if (isCertainVR)
            {
                if (StreamFile.Read(Constants.ReservedLenght).ToUInt16() != 0)
                    throw new ArgumentException("Reserved 2 bytes block is not 0x0000.");

                SetImplicitLenght((uint)StreamFile.Read(Constants.ImplicitValueLenght).ToUInt32());
            }
            else if (TransferSyntax.IsImplicitVR || vr.IsImplicit)
                SetImplicitLenght((uint)StreamFile.Read(Constants.ImplicitValueLenght).ToUInt32());
            else
                SetLenght(StreamFile.Read(Constants.emplicitValueLenght).ToUInt16());
        }
        private void SetImplicitLenght(uint lenght)
        {
            if (lenght == 0xFFFFFFFF)
            {
                _valueLength = -1;
            }
            else if (lenght > int.MaxValue)
                throw new Exception("Value length is too big for this implementation.");
            else
                _valueLength = (int)lenght;
        }
        private void SetLenght(int lenght)
        {
            _valueLength = lenght;
        }
        #endregion
    }
}
